<template>
	<view class="loginAll">
		<ul class="tab">
			<li v-for="(list,index) in listData" :key="index" :class="index==isIndex?'active':''"
				@click="tabChange(index)" style="margin-left: 0upx;">{{list}}</li>
		</ul>
		<view class="list" v-if="tabShow">

			<view class="uik" style="display: flex; align-items: center;">
				<li style="font-size:32upx;width:160upx">手机号:</li>
				<view style="width:10upx;"></view>
				<li><input type="number" value="" v-model="phone" maxlength="11" placeholder=" 请输入手机号" /></li>

				<view style="width: 190upx;">

				</view>

			</view>
			<view class="uik" style="display: flex; align-items: center;">
				<li style="font-size:32upx;width:160upx;">验证码:</li>
				<view style="width:10upx;"></view>
				<li><input type="number" value="" maxlength="4" v-model="yzm" placeholder=" 请输入验证码" /></li>
				<view v-if="showText==true" class="btn" @click="appSms">发送验证码</view>
				<view v-else class="btn">{{second}}s重新发送</view>
			</view>
		</view>
		<view class="list" v-else>
			<ul>
				<li>账号：</li>
				<li class="li2"><input type="text" value="" maxlength="11" v-model="account"
						placeholder=" 请输入哩咔ID或注册手机号" /></li>
			</ul>
			<ul>
				<li>密码：</li>
				<li class="li2"><input type="password" value="" v-model="password" placeholder=" 请输入密码（6-12位数字加字母组合）" />
				</li>
			</ul>
		</view>
		<view class="login" @click="phoneOrNoLogin">
			登录
		</view>
		<view class="text">
			<view class="circle" @click="cirChange">
				<view class="cir" v-if="cirShow"></view>
			</view>
			<view class="tip">登录即同意
				<text style="color: #fd3333;" @click="goArgument">《用户协议》</text>和
				<text style="color: #fd3333;" @click="goPrivacy">《隐私政策》</text>
			</view>
		</view>

	</view>
</template>

<script>
	import Vue from "vue";
	import SDK from "@/commons/NIM_Web_SDK_miniapp_v8.5.0.js";
	import {
		decrypt,
		encrypt,
		signature,
		CreateIM
	} from "@/commons/util.des.js";
	export default {
		data() {
			return {
				yzm: '',
				second: 60,
				showText: true,
				phone: '',
				account: '13100000070',
				password: '123456',
				listData: ['验证码登录'],
				// listData: ['验证码登录', "id"],
				isIndex: 0,
				tabShow: true,
				cirShow: true,
				rateX: '',
				token: '',
				xxid: '',

				tapTime: 0,
				// 防止两次点击操作间隔太快
			}
		},
		mounted() {

			if (this.$BASE_URL == "https://webapp.shenghua6.cn") {
				this.listData = ['验证码登录']
			} else {
				this.listData = ['验证码登录', "id"]
			}


		},

		methods: {


			// 防止恶意点击
			fangdou: function() {
				var nowTime = Math.round(new Date());
				console.log('距离上次点击', nowTime - this.tapTime, '毫秒')
				if (nowTime - this.tapTime < 300) {
					console.log('阻断')
					this.tapTime = nowTime
					return false;
				} else {
					this.tapTime = nowTime
					return true
					console.log('执行')
				}

			},



			getCode() { //倒计时
				this.showText = false
				var interval = setInterval(() => {
					let times = --this.second
					this.second = times < 10 ? '0' + times : times //小于10秒补 0
				}, 1000)
				setTimeout(() => {
					clearInterval(interval)
					this.second = 60
					this.showText = true
				}, 60000)
			},
			tabChange(index) {
				if (index == 0) {
					this.tabShow = true
				} else {
					this.tabShow = false
				}
				this.isIndex = index
			},
			cirChange() {
				this.cirShow = !this.cirShow
			},
			goArgument() {
				uni.navigateTo({
					url: './argument'
				})
			},
			goPrivacy() {
				uni.navigateTo({
					url: './privacy'
				})
			},
			appSms() {

				var re = this.fangdou()

				if (!re) {
					console.log('不行')
					return
				}



				if (!(/^1[3456789]\d{9}$/.test(this.phone))) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none',
						duration: 2000
					});
					return
				}

				var data = {
					url: '/web/v2/api/app/appSms',
					methods: 'post',
					data: {
						smsCategory: 16,
						phone: this.phone
					}
				}
				this.$http(data).then(res => {

					if (res.data.code == 21000) {
						this.getCode()
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			phoneOrNoLogin() {


				var re = this.fangdou()

				if (!re) {
					console.log('不行')
					return
				}


				var _this = this
				if (!this.cirShow) {
					uni.showToast({
						title: '请先勾选同意用户协议',
						icon: 'none',
						duration: 2000
					});
				} else {

					if (this.tabShow) {
						if (!(/^1[3456789]\d{9}$/.test(this.phone))) {
							uni.showToast({
								title: '手机号格式不正确',
								icon: 'none',
								duration: 2000
							});
							return
						}

						var patt1 = new RegExp(/\s+/g);
						if (patt1.test(this.yzm)) {
							uni.showToast({
								title: '请填写正确验证码',
								icon: 'none',
								duration: 2000
							});
							return
						}

						if (this.yzm.length < 4) {
							uni.showToast({
								title: '请填写正确验证码',
								icon: 'none',
								duration: 2000
							});
							return
						}

						var data = {
							url: '/web/v2/api/app/smsLogin',
							methods: 'post',
							data: {
								authCode: this.yzm,
								phone: this.phone,
							}
						}
						this.$http(data).then(res => {

							console.log('小程序授权im实例化接口6666666666', res.data)
							if (res.data.code == 21000) {




								var gllist = getApp().globalData
								if (res.data.code == 21000) {


									// #ifdef  MP-WEIXIN   

									// 登录埋点
									// AuthorizedLoginResult 埋点名称

									// login_method	登录方式	STRING	手机号/微信/
									console.log('登陆埋点', getApp().sensors)
									getApp().sensors.track('AuthorizedLoginResult', {

										login_method: '手机号'

									})

									// #endif

									// 建立全局im
									CreateIM(res.data.data.userId, res.data.data.imPwd, res)
									return



									//  IM实例化

									Vue.prototype.$NIM = SDK.NIM.getInstance({
										debug: true,
										appKey: "7ca5cef23fd00cb4774107175ab6d413",
										account: res.data.data.userId,
										token: decrypt(res.data.data.imPwd),
										onconnect: onConnect,
										ondisconnect: onDisconnect,
										// 收到会话列表
										onWillReconnect: onWillReconnect,
										onsessions: onSessions,
										onupdatesession: onUpdateSession,
										// 消息接受
										onmsg: onMsg
									});

									function onSessions(sessions) {
										console.log('收到会话列表', sessions);
										// getApp().globalData.list= sessions

										gllist.sessions = _this.$NIM.mergeSessions(gllist.sessions, sessions);
										updateSessionsUI();
									}

									function onUpdateSession(session) {
										console.log('会话更新了3213666', session);
										gllist.sessions = _this.$NIM.mergeSessions(gllist.sessions, session);
										updateSessionsUI(session);
									}

									function updateSessionsUI(session) {
										// 刷新界面
										console.log('刷新页面1')


										uni.$emit('update', {
											addrsssid: '更新列表操作',
										});

										uni.$emit('updateHH', {
											addrsssid: session,
										});

									}


									function onMsg(msg) {
										console.log('收到消息6666', msg.scene, msg.type, msg);
										// pushMsg(msg);
										switch (msg.type) {
											case 'custom':
												onCustomMsg(msg);
												break;
											case 'notification':
												// 处理群通知消息
												onTeamNotificationMsg(msg);
												break;
												// 其它case
											default:
												break;
										}
									}




									var nei = {
										appKey: "7ca5cef23fd00cb4774107175ab6d413",
										account: res.data.data.userId,
										token: decrypt(res.data.data.imPwd),
									}


									uni.setStorage({
										key: 'nei',
										data: nei,
										success: function() {
											console.log('success');
										}
									});



									// 是否首次登录

									uni.setStorage({
										key: 'shifoushouci',
										data: res.data.data.loginType,
										success: function() {
											console.log('success');
										}
									});


									function onConnect() {
										console.log("登录页=========================IM连接成功");
									}


									function onWillReconnect(obj) {
										// 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
										console.log('即将重连');
										console.log(obj.retryCount);
										console.log(obj.duration);

										uni.showToast({
											title: '正在连接...',
											icon: 'none',
											duration: 2000
										});


									}


									function onDisconnect(error) {
										// 此时说明 SDK 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面


										// uni.showToast({
										// 	title: '连接丢失...',
										// 	icon: 'none',
										// 	duration: 2000
										// });
										console.log("丢失连接");
										console.log(error);
										if (error) {
											switch (error.code) {
												// 账号或者密码错误, 请跳转到登录页面并提示错误
												case 302:
													break;
													// 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
												case 417:
													break;
													// 被踢, 请提示错误后跳转到登录页面
												case "kicked":
													console.log("kicked");

													if (error.reason == "samePlatformKick") {
														uni.showToast({
															title: "您的帐号在异地登陆",
															duration: 2000,
															icon: "none",
														});
														setTimeout(function() {
															//清除本地登录状态
															// uni.clearStorage();
															// 清除本地cookie
															uni.removeStorage({key: 'cookie'});
															//IM实例销毁
															Vue.prototype.$NIM.disconnect();

															//跳转登录页
															uni.redirectTo({
																url: "/pages/login/wxlogin",
															});
														}, 2000);
													}


													if (error.reason == "serverKick") {
														uni.showToast({
															title: "您的帐号已被封禁",
															duration: 2000,
															icon: "none",
														});
														setTimeout(function() {
															//清除本地登录状态
															// uni.clearStorage();
															// 清除本地cookie
															uni.removeStorage({key: 'cookie'});
															//IM实例销毁
															Vue.prototype.$NIM.disconnect();

															//跳转登录页
															uni.redirectTo({
																url: "/pages/login/wxlogin",
															});
														}, 2000);


													}



													default:
														break;
											}
										}
									}
								}




								var cookie = 'sfc0327fd=a81b6mhujnloqjhuhlc23lkleq; path=/'
								// var cookie = '4p4hmta4bhil268cqmokegrqla'



								// #ifdef MP-WEIXIN
								// 需条件编译的代码
								var cookie = res.header["Set-Cookie"];
								console.log(cookie, "cookid")
								// #endif








								console.log(cookie, "cookiecookie4")


								uni.setStorage({
									key: 'cookie',
									data: cookie,
									success: function() {
										console.log('success');
									}
								});

								uni.setStorage({
									key: 'userInfo',
									data: res.data.data,
									success: function() {
										console.log('success');
									}
								});




								console.log('登录sessionId', res.data.sessionId)
								//  
								// uni.setStorage({
								// 	key: 'sessionid',
								// 	data: res.data.sessionId,
								// 	success: function() {
								// 		console.log('success');
								// 	}
								// });
								uni.switchTab({
									url: '../index/index'
								})
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 2000
								});
							}
						})
					} else {
						var data = {
							url: '/web/v2/api/app/phoneOrNoLogin',
							methods: 'post',
							data: {
								account: encrypt({
									ID: this.account,
									password: this.password,
								})
							}
						}
						this.$http(data).then(res => {
							if (res.data.code == 21000) {
								var _this = this


								 
								CreateIM(res.data.data.userId, res.data.data.imPwd, res)
								return


								console.log(res, "登录返回")
								 

								var gllist = getApp().globalData

								if (res.data.code == 21000) {
									//  IM实例化
									Vue.prototype.$NIM = SDK.NIM.getInstance({

										debug: true,

										appKey: "7ca5cef23fd00cb4774107175ab6d413",
										account: res.data.data.userId,
										token: decrypt(res.data.data.imPwd),

										// im登陆成功
										onconnect: onConnect,
										// im 断开
										onWillReconnect: onWillReconnect,
										ondisconnect: onDisconnect,
										// 收到会话列表
										onsessions: onSessions,
										onupdatesession: onUpdateSession,
										// 消息接受
										onmsg: onMsg

									});

									_this.$NIM
									 

									function onSessions(sessions) {
										console.log('收到会话列表', sessions);
										gllist.sessions = _this.$NIM.mergeSessions(gllist.sessions, sessions);

										 
										for (var i = 0; i < gllist.sessions.length; i++) {
											updateSessionsUI(gllist.sessions[i]);
										}
									}

									function onUpdateSession(session) {

										//  
										// "custom"  自定义消息  
										// "audio"  语音消息
										// "image"  图片消息
										// "text"   文本消息

										console.log('会话更新了123', session.lastMsg.type);
										var type = session.lastMsg.type
										gllist.sessions = _this.$NIM.mergeSessions(gllist.sessions, session);
										updateSessionsUI(session);
									}

									function updateSessionsUI(session) {
										// 刷新界面
										// gllist.sessions
										if (session) {
											var type = session.lastMsg.type

											if (type == "custom") {
												console.log('会话更新暂不支持此类型消息')
												return
											}


											// 判断id 相同的情况下 禁止更新聊天
											if (_this.xxid == session.lastMsg.idServer) {
												return
											}
											// 赋值全局消息id
											_this.xxid = session.lastMsg.idServer

											//  

											if (session.lastMsg.status != "success") {
												return

											}


											var use = gllist[session.id]


											if (use) {
												var d = gllist[session.id]

												// 储存聊天信息
												gllist[session.id].push(session.lastMsg);
											} else {
												// 储存聊天信息
												gllist[session.id] = []
												gllist[session.id].push(session.lastMsg);

											}




											console.log('全局储存的聊天记录', gllist)

											console.log('更新会话列表')

											uni.$emit('update', {
												addrsssid: '更新操作',
											});


										}
									}

									function onMsg(msg) {

										console.log('收到消息6666', msg.scene, msg.type, msg);

									}




									var nei = {
										appKey: "7ca5cef23fd00cb4774107175ab6d413",
										account: res.data.data.userId,
										token: decrypt(res.data.data.imPwd),

									}



									// 是否首次登录

									uni.setStorage({
										key: 'shifoushouci',
										data: res.data.data.loginType,
										success: function() {
											console.log('success');
										}
									});



									function onConnect() {
										console.log("登录页=========================IM连接成功 帐号id登录的 ");
									}


									function onWillReconnect(obj) {
										// 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
										console.log('即将重连');
										console.log(obj.retryCount);
										console.log(obj.duration);

										uni.showToast({
											title: '正在连接...',
											icon: 'none',
											duration: 2000
										});


									}


									function onDisconnect(error) {
										// 此时说明 SDK 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
										console.log("丢失连接");

										// uni.showToast({
										// 	title: '连接丢失...',
										// 	icon: 'none',
										// 	duration: 2000
										// });

										console.log(error);
										if (error) {
											switch (error.code) {
												// 账号或者密码错误, 请跳转到登录页面并提示错误
												case 302:
													break;
													// 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
												case 417:
													break;
													// 被踢, 请提示错误后跳转到登录页面
												case "kicked":
													console.log("kicked");

													if (error.reason == "samePlatformKick") {
														uni.showToast({
															title: "您的帐号在异地登陆",
															duration: 2000,
															icon: "none",
														});
														setTimeout(function() {
															//清除本地登录状态
															// uni.clearStorage();
															// 清除本地cookie
															uni.removeStorage({key: 'cookie'});
															//IM实例销毁
															Vue.prototype.$NIM.disconnect();

															//跳转登录页
															uni.redirectTo({
																url: "/pages/login/wxlogin",
															});
														}, 2000);
													}
													break;
												default:
													break;
											}
										}
									}
								}



								var cookie = '4p4hmta4bhil268cqmokegrqla'
								// var ss = res.header["Set-Cookie"];
								//  
								console.log(cookie, "cookiecookie4")



								// #ifdef MP-WEIXIN
								// 需条件编译的代码
								var cookie = res.header["Set-Cookie"];
								console.log(cookie, "cookid")
								// #endif



								uni.setStorage({
									key: 'nei',
									data: nei,
									success: function() {
										console.log('success');
									}
								});


								uni.setStorage({
									key: 'cookie',
									data: cookie,
									success: function() {
										console.log('success');
									}
								});


								uni.setStorage({
									key: 'userInfo',
									data: res.data.data,
									success: function() {
										console.log('success');
									}
								});
								console.log('登录sessionId', res.data.sessionId)

								uni.switchTab({
									url: '../index/index'
								})



							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 2000
								});
							}
						})
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.y {
		width: 50%;
		// border: 1px solid #1989FA;
		float: left;

	}

	.n {
		width: 95%;

		font-size: 24rpx;
		margin: 0 auto;
		border: 1rpx solid #F1F1F1;
		border-radius: 10rpx;


	}

	.nimg {
		width: 100%;

	}


	.nbot {
		display: flex;
		line-height: 70rpx;
		align-items: center;
	}

	.anniu {
		margin-left: auto;
		text-align: center;
		width: 100rpx;
	}



	input {
		caret-color: #fd3333;
	}

	input::-webkit-input-placeholder {
		caret-color: #fd3333;
	}


	.tab {
		font-size: 24upx;
		color: #333333;
		display: flex;
		font-weight: bold;
		align-items: center;
		justify-content: center;

		li:last-child {
			margin-left: 80upx;
		}
	}

	.list {
		margin-top: 30upx;

		.uik {
			display: flex;
			align-items: center;
			height: 97upx;
			margin: 0 50upx;
			border-bottom: 1px solid #e0e0e0;
			padding-top: 18upx;
			padding-left: 27upx;
			font-size: 36upx;
			font-weight: bold;
			color: #333333;
		}

		ul {
			display: flex;
			align-items: center;
			height: 97upx;
			margin: 0 50upx;
			border-bottom: 1px solid #e0e0e0;
			padding-top: 18upx;
			padding-left: 27upx;
			font-size: 36upx;
			font-weight: bold;
			color: #333333;
		}



		.li2 {
			flex: 1;
		}

		input {
			font-size: 24upx;
			color: #acacac;
			width: 80%;

		}

		.btn {
			width: 190upx;


			height: 60upx;
			line-height: 60upx;
			background-image: linear-gradient(90deg,
					#642afd 0%,
					#bc43ff 100%),
				linear-gradient(#ffffff,
					#ffffff);
			background-blend-mode: normal,
				normal;
			box-shadow: 0px 4upx 18upx 0px rgba(78, 15, 232, 0.47);
			border-radius: 30upx;
			font-size: 22upx;
			font-weight: bold;
			text-align: center;
			color: #ffffff;
			margin-left: auto;
		}
	}

	.active {
		font-size: 36upx;

	}

	.login {
		width: 460upx;
		height: 88upx;
		line-height: 88upx;
		background-image: linear-gradient(90deg,
				#642afd 0%,
				#bc43ff 100%),
			linear-gradient(#ffffff,
				#ffffff);
		background-blend-mode: normal,
			normal;
		box-shadow: 0px 4upx 18upx 0upx rgba(78, 15, 232, 0.47);
		border-radius: 44upx;
		font-size: 30upx;
		font-weight: bold;
		text-align: center;
		color: #ffffff;
		margin: 0 auto;
		margin-top: 230upx;
	}

	.circle {
		width: 30upx;
		height: 30upx;
		border: solid 2upx #fd4849;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 8upx;

		.cir {
			width: 14upx;
			height: 14upx;
			background-color: #fd4849;
			border-radius: 50%;
		}
	}

	.text {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20upx;
		font-weight: bold;
		color: #666666;
		position: fixed;
		bottom: 76upx;
	}
</style>
